from json.encoder import JSONEncoder
from django.shortcuts import render
from django.http import JsonResponse
from django.views.generic import View
from goods.models import GoodsSKU
from django_redis import get_redis_connection
from django.contrib.auth.decorators import login_required
# Create your views here.


@login_required
def cart(request):
    user = request.user

    conn = get_redis_connection('history')
    cart_key = 'cart_%d' % user.id
    total_count = conn.hlen(cart_key)
    goods_count = conn.hgetall(cart_key)
    goods_list = []
    for i in range(len(goods_count)):
        sku_id = list(goods_count.keys())[i].decode()
        sku_count = list(goods_count.values())[i].decode()
        try:
            goods = GoodsSKU.objects.get(id=sku_id)
        except:
            print('商品名：%s,商品id：%    不存在！' % (goods.name, goods.id))
        goods.sku_count = sku_count
        # 把商品的小计也在这里计算掉
        goods.small_total = goods.price * int(sku_count)
        # 把商品库存也传过去
        goods.sku_stock = goods.stock
        goods_list.append(goods)
    context = {
        'total_count': total_count,
        'goods_list': goods_list,
    }
    return render(request, 'cart/cart.html', context=context)

# 这个不能用用户登录模块的类方法来装饰 因为这个是ajax的请求链接 而这些请求都在后台 看不到 所以即使跳转到登录页面了 我们也看不到 所以判断用户有没有登录，没有登录就响应对应的json消息提醒


class Add_cart(View):
    def post(self, request):
        user = request.user
        # 判断是否登录
        if not user.is_authenticated:
            return JsonResponse({'res': 0, 'errmsg': '请登录'})

        # 接收数据
        sku_id = request.POST.get('sku_id')
        count = request.POST.get('count')

        if not all([sku_id, count]):
            return JsonResponse({'res': 1, 'errmsg': '数据不完整'})

        try:
            count = int(count)
        except:
            return JsonResponse({'res': 2, 'errmsg': '商品数量出错'})

        try:
            sku = GoodsSKU.objects.get(id=sku_id)
        except:
            return JsonResponse({'res': 3, 'errmsg': '商品sku不存在'})

        conn = get_redis_connection('history')
        cart_key = 'cart_%d' % user.id
        # 先看看购物车里是否已经存在，是否要更新累加数目
        cart_count = conn.hget(cart_key, sku.id)  # 找不到返回none 不会出错
        if cart_count:
            # 累加数量
            count += int(cart_count)

        # 校验商品的库存
        if count > sku.stock:
            return JsonResponse({'res': 4, 'errmsg': '商品库存不足'})

        conn.hset(cart_key, sku.id, count)  # 没有则增加，有则更新

        total_count = conn.hlen(cart_key)

        # 成功应答
        return JsonResponse({'res': 5, 'total_count': total_count, 'message': '添加购物车成功'})


class Remove_cart(View):
    def post(self, request):
        # 接收数据
        user = request.user
        # 判断是否登录
        if not user.is_authenticated:
            return JsonResponse({'res': 0, 'errmsg': '请登录'})

        sku_id = request.POST.get('sku_id')

        if not sku_id:
            return JsonResponse({'res': 2, 'errmsg': '数据不完整'})

        conn = get_redis_connection('history')
        cart_key = 'cart_%d' % user.id

        conn.hdel(cart_key, sku_id)
        count = conn.hlen(cart_key)

        return JsonResponse({'res': 1, 'count': count, 'msg': '该商品已删除'})


class Updata_cart(View):
    def post(self, request):
        user = request.user
        # 判断是否登录
        if not user.is_authenticated:
            return JsonResponse({'res': 0, 'errmsg': '请登录'})

        # 接收数据
        sku_id = request.POST.get('sku_id')
        count = request.POST.get('count')

        if not all([sku_id, count]):
            return JsonResponse({'res': 1, 'errmsg': '数据不完整'})

        try:
            count = int(count)
        except:
            return JsonResponse({'res': 2, 'errmsg': '商品数量出错'})

        try:
            sku = GoodsSKU.objects.get(id=sku_id)
        except:
            return JsonResponse({'res': 3, 'errmsg': '商品sku不存在'})

        conn = get_redis_connection('history')
        cart_key = 'cart_%d' % user.id

        # 校验商品的库存
        if count > sku.stock:
            return JsonResponse({'res': 4, 'errmsg': '商品库存不足', 'sku_stock': sku.stock})

        conn.hset(cart_key, sku_id, count)

        return JsonResponse({'res': 5, 'errmsg': '更新成功'})

